using Microsoft.AspNetCore.Mvc;
using SheLife.Application.Interfaces;
using SheLife.Domain.Entities;

namespace SheLife.Api.Controllers
{
    /// <summary>
    /// 习惯记录管理控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class HabitRecordsController : ControllerBase
    {
        private readonly IHabitRecordService _habitRecordService;

        public HabitRecordsController(IHabitRecordService habitRecordService)
        {
            _habitRecordService = habitRecordService;
        }

        /// <summary>
        /// 获取习惯记录详情
        /// </summary>
        /// <param name="id">习惯记录ID</param>
        /// <returns>习惯记录详情</returns>
        [HttpGet("{id}")]
        public async Task<IActionResult> GetHabitRecord(Guid id)
        {
            var habitRecord = await _habitRecordService.GetHabitRecordByIdAsync(id);
            if (habitRecord == null)
            {
                return NotFound();
            }

            return Ok(habitRecord);
        }

        /// <summary>
        /// 获取用户的习惯记录列表
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="habitId">习惯ID</param>
        /// <param name="date">日期</param>
        /// <param name="startDate">开始日期</param>
        /// <param name="endDate">结束日期</param>
        /// <returns>习惯记录列表</returns>
        [HttpGet]
        public async Task<IActionResult> GetHabitRecords(
            [FromQuery] Guid userId,
            [FromQuery] Guid? habitId = null,
            [FromQuery] DateTime? date = null,
            [FromQuery] DateTime? startDate = null,
            [FromQuery] DateTime? endDate = null)
        {
            var habitRecords = await _habitRecordService.GetHabitRecordsByUserIdAsync(userId, habitId, date, startDate, endDate);
            return Ok(habitRecords);
        }

        /// <summary>
        /// 获取习惯的记录列表
        /// </summary>
        /// <param name="habitId">习惯ID</param>
        /// <param name="startDate">开始日期</param>
        /// <param name="endDate">结束日期</param>
        /// <returns>习惯记录列表</returns>
        [HttpGet("by-habit/{habitId}")]
        public async Task<IActionResult> GetHabitRecordsByHabitId(
            Guid habitId,
            [FromQuery] DateTime? startDate = null,
            [FromQuery] DateTime? endDate = null)
        {
            var habitRecords = await _habitRecordService.GetHabitRecordsByHabitIdAsync(habitId, startDate, endDate);
            return Ok(habitRecords);
        }

        /// <summary>
        /// 创建习惯记录
        /// </summary>
        /// <param name="model">习惯记录创建模型</param>
        /// <returns>创建的习惯记录</returns>
        [HttpPost]
        public async Task<IActionResult> CreateHabitRecord([FromBody] CreateHabitRecordModel model)
        {
            try
            {
                var habitRecord = await _habitRecordService.CreateHabitRecordAsync(
                    model.UserId,
                    model.HabitId,
                    model.RecordDate,
                    model.Value,
                    model.Notes);

                return CreatedAtAction(nameof(GetHabitRecord), new { id = habitRecord.Id }, habitRecord);
            }
            catch (ArgumentException ex)
            {
                return BadRequest(new { message = ex.Message });
            }
        }

        /// <summary>
        /// 标记习惯记录为已完成
        /// </summary>
        /// <param name="id">习惯记录ID</param>
        /// <returns>更新后的习惯记录</returns>
        [HttpPost("{id}/complete")]
        public async Task<IActionResult> MarkHabitRecordAsCompleted(Guid id)
        {
            var habitRecord = await _habitRecordService.MarkHabitRecordAsCompletedAsync(id);
            if (habitRecord == null)
            {
                return NotFound();
            }

            return Ok(habitRecord);
        }

        /// <summary>
        /// 标记习惯记录为未完成
        /// </summary>
        /// <param name="id">习惯记录ID</param>
        /// <returns>更新后的习惯记录</returns>
        [HttpPost("{id}/incomplete")]
        public async Task<IActionResult> MarkHabitRecordAsIncompleted(Guid id)
        {
            var habitRecord = await _habitRecordService.MarkHabitRecordAsIncompletedAsync(id);
            if (habitRecord == null)
            {
                return NotFound();
            }

            return Ok(habitRecord);
        }

        /// <summary>
        /// 更新习惯记录备注
        /// </summary>
        /// <param name="id">习惯记录ID</param>
        /// <param name="model">备注更新模型</param>
        /// <returns>更新后的习惯记录</returns>
        [HttpPut("{id}/notes")]
        public async Task<IActionResult> UpdateHabitRecordNotes(Guid id, [FromBody] UpdateNotesModel model)
        {
            var habitRecord = await _habitRecordService.UpdateHabitRecordNotesAsync(id, model.Notes);
            if (habitRecord == null)
            {
                return NotFound();
            }

            return Ok(habitRecord);
        }

        /// <summary>
        /// 删除习惯记录
        /// </summary>
        /// <param name="id">习惯记录ID</param>
        /// <returns>删除结果</returns>
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteHabitRecord(Guid id)
        {
            var result = await _habitRecordService.DeleteHabitRecordAsync(id);
            if (!result)
            {
                return NotFound();
            }

            return Ok(new { message = "习惯记录删除成功" });
        }

        /// <summary>
        /// 获取护肤习惯记录
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="date">日期</param>
        /// <returns>护肤习惯记录列表</returns>
        [HttpGet("skincare")]
        public async Task<IActionResult> GetSkincareHabitRecords(
            [FromQuery] Guid userId,
            [FromQuery] DateTime? date = null)
        {
            var habitRecords = await _habitRecordService.GetHabitRecordsByUserIdAsync(userId, null, date, null, null);
            
            // 筛选出护肤类型的习惯记录
            var skincareRecords = habitRecords.Where(hr => hr.Habit?.Type == "Skincare").ToList();
            
            return Ok(skincareRecords);
        }

        /// <summary>
        /// 创建护肤习惯记录
        /// </summary>
        /// <param name="model">护肤习惯记录创建模型</param>
        /// <returns>创建的护肤习惯记录</returns>
        [HttpPost("skincare")]
        public async Task<IActionResult> CreateSkincareHabitRecord([FromBody] CreateSkincareHabitRecordModel model)
        {
            try
            {
                // 将护肤步骤数据序列化为JSON
                var data = new
                {
                    model.CompletedSteps,
                    model.UsedProducts,
                    model.SkinCondition,
                    model.Duration
                };

                var habitRecord = await _habitRecordService.CreateHabitRecordAsync(
                    model.UserId,
                    model.HabitId,
                    model.RecordDate,
                    model.CompletedSteps?.Count ?? 0,
                    System.Text.Json.JsonSerializer.Serialize(data));

                return CreatedAtAction(nameof(GetHabitRecord), new { id = habitRecord.Id }, habitRecord);
            }
            catch (ArgumentException ex)
            {
                return BadRequest(new { message = ex.Message });
            }
        }
    }

    /// <summary>
    /// 习惯记录创建模型
    /// </summary>
    public class CreateHabitRecordModel
    {
        /// <summary>
        /// 用户ID
        /// </summary>
        public Guid UserId { get; set; }

        /// <summary>
        /// 习惯ID
        /// </summary>
        public Guid HabitId { get; set; }

        /// <summary>
        /// 记录日期
        /// </summary>
        public DateTime RecordDate { get; set; }

        /// <summary>
        /// 完成值
        /// </summary>
        public int? Value { get; set; }

        /// <summary>
        /// 备注
        /// </summary>
        public string? Notes { get; set; }
    }

    /// <summary>
    /// 备注更新模型
    /// </summary>
    public class UpdateNotesModel
    {
        /// <summary>
        /// 备注
        /// </summary>
        public string? Notes { get; set; }
    }

    /// <summary>
    /// 护肤习惯记录创建模型
    /// </summary>
    public class CreateSkincareHabitRecordModel
    {
        /// <summary>
        /// 用户ID
        /// </summary>
        public Guid UserId { get; set; }

        /// <summary>
        /// 习惯ID
        /// </summary>
        public Guid HabitId { get; set; }

        /// <summary>
        /// 记录日期
        /// </summary>
        public DateTime RecordDate { get; set; }

        /// <summary>
        /// 完成的步骤
        /// </summary>
        public List<CompletedStep>? CompletedSteps { get; set; }

        /// <summary>
        /// 使用的产品
        /// </summary>
        public List<UsedProduct>? UsedProducts { get; set; }

        /// <summary>
        /// 皮肤状况
        /// </summary>
        public string? SkinCondition { get; set; }

        /// <summary>
        /// 护肤时长（分钟）
        /// </summary>
        public int? Duration { get; set; }
    }

    /// <summary>
    /// 完成的步骤
    /// </summary>
    public class CompletedStep
    {
        /// <summary>
        /// 步骤名称
        /// </summary>
        public string Name { get; set; } = string.Empty;

        /// <summary>
        /// 步骤顺序
        /// </summary>
        public int Order { get; set; }

        /// <summary>
        /// 是否完成
        /// </summary>
        public bool IsCompleted { get; set; } = true;

        /// <summary>
        /// 完成时间
        /// </summary>
        public DateTime? CompletedAt { get; set; }

        /// <summary>
        /// 备注
        /// </summary>
        public string? Notes { get; set; }
    }

    /// <summary>
    /// 使用的产品
    /// </summary>
    public class UsedProduct
    {
        /// <summary>
        /// 产品名称
        /// </summary>
        public string Name { get; set; } = string.Empty;

        /// <summary>
        /// 品牌
        /// </summary>
        public string? Brand { get; set; }

        /// <summary>
        /// 产品类型
        /// </summary>
        public string? Type { get; set; }

        /// <summary>
        /// 使用步骤
        /// </summary>
        public int Step { get; set; }

        /// <summary>
        /// 使用量
        /// </summary>
        public string? Amount { get; set; }
    }
}